package com.aistar.controller;

import com.aistar.exception.SecKillException;
import com.aistar.pojo.Customer;
import com.aistar.service.SeckillService;
import com.aistar.util.DateUtil;
import com.aistar.util.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
public class SeckillController {

    @Autowired
    @Qualifier("seckillServiceImpl")
    private SeckillService seckillService;

    @GetMapping("/getproInSeckill/{pageNum}")
    @ResponseBody
    public ServerResponse getTime(@PathVariable("pageNum") Integer page){

        if (page==null){
            page=1;
        }
        Date nowTime = new Date();

        ServerResponse serverResponse = seckillService.getproByTime(nowTime,page);
        System.out.println("controller serverResponse:"+serverResponse);
        return serverResponse;

    }

    @GetMapping("/seckill/getcount")
    @ResponseBody
    public ServerResponse getCount(Integer  seckillId){
        return  seckillService.getCountBySeckill(seckillId);

    }
    @PostMapping("/seckill/rob")
    @ResponseBody
    public Map  processSeckill(Integer seckillId, HttpServletRequest request){
        Customer customer = (Customer)request.getSession().getAttribute("loginCustomer");
        Integer userId = customer.getCustomerId();
        System.out.println("userId::::"+userId);
        Map result = new HashMap();
        try {
            seckillService.processSeckill(seckillId,userId,1);
            result.put("code","0");
            result.put("message","success");

        } catch (SecKillException e) {
            result.put("code","500");
            result.put("message",e.getMessage());
        }
        return result;
    }

    //首页跳转秒杀页面
    @RequestMapping("/toSeckill")
    public String toSeckill(){
        return "/product/secKill";
    }
}
